package com.antu.first.web.merchant;

import com.alibaba.fastjson.JSON;
import com.antu.first.util.ImageHandle;
import net.sf.json.JSONArray;
import com.antu.first.bean.Hotel;
import com.antu.first.bean.Merchant;
import com.antu.first.bean.Swiper;
import com.antu.first.dto.ImageHolder;
import com.antu.first.dto.SwiperOperationExecution;
import com.antu.first.exceptions.SwiperOperationException;
import com.antu.first.service.SwiperService;
import com.antu.first.util.CodeUtil;
import com.antu.first.util.HttpServletRequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * Created by Administrator on 2018/3/6.
 */
@Controller
@RequestMapping("/swiperController")
public class SwiperController {
    @Autowired
    SwiperService swiperService;
    private static final int IMAGEMAXCOUNT = 6;

    public Map<String, Object> toPromoteSwiper(Integer swStatus) {
        return swiperService.toPromoteSwiper(swStatus);
    }

    /**
     * 按照酒店ＩＤ和轮播图ID更新轮播图信息
     *
     * @param swiper
     * @return
     */
    @RequestMapping(value = "/updateSwiperById")
    @ResponseBody
    public Map<String, Object> updateSwiperById(Swiper swiper) {
        return swiperService.updateSwiperById(swiper);
    }

    /**
     * 获取当前酒店的轮播图（多条件，显示位置，图片权重，图片状态）
     *
//     * @param swiper      查询条件
     * @param currentPage 当前页码
     * @param pageSize    每页条数，不传默认10条
     * @return
     */
    @RequestMapping(value = "/allSwiperByHotelId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> allSwiperByHotelId(String swName, String swDesc, String swLoc, Integer currentPage, Integer pageSize, HttpServletRequest httpServletRequest) {
        Merchant merchant = (Merchant) httpServletRequest.getSession().getAttribute("merchant");//取出对象
        Swiper swiper = new Swiper();
        swiper.setSwName(swName);
        swiper.setSwDesc(swDesc);
        if(swLoc!=null&&swLoc!=""){
            swiper.setSwLoc(Integer.parseInt(swLoc));
        }
        swiper.setHotel(merchant.getHotel());
        return swiperService.allSwiperByHotelId(swiper, currentPage, pageSize);
    }

    /**
     * 轮播图上传，前端传入轮播图的过程中，需要确定swDesc,swName,swSequence
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/addSwipers", method = RequestMethod.POST)
    @ResponseBody
    public String addSwipers(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //Hotel hotel= (Hotel) request.getSession().getAttribute("hotel");

        List<Swiper> swiperList = new ArrayList<Swiper>();
        String swipers = request.getParameter("swiperList");
        JSONArray jsonArray = JSONArray.fromObject(swipers);
        swiperList = JSONArray.toList(jsonArray, Swiper.class);

        System.out.println(swipers);

        List<ImageHolder> swiperImgList = new ArrayList<ImageHolder>();
        //从Servlet容器中获取CommonsMultipart解析器
        CommonsMultipartResolver multipartResolver =
                new CommonsMultipartResolver(request.getServletContext());

        System.out.println(multipartResolver.isMultipart(request));

        //首先获取图片信息
        try {
            if (multipartResolver.isMultipart(request)) {
                //把Swiper的图片信息写入到swiperImgList中去
                ImageHandle.handleImage(request, swiperImgList);
            } else {
                modelMap.put("success", false);
                modelMap.put("errMsg", "上传图片不能为空");
                System.out.println(modelMap);
                return JSON.toJSONString(modelMap);
            }
        } catch (Exception e) {
            throw new SwiperOperationException("SwiperController-addaddSwipers,在处理轮播图信息的过程中发生异常：" + e.toString());
        }
        //取出图片信息后，验证文本信息是否正确
        System.out.println("-----------------");
        if (swiperList != null && swiperList.size() > 0 && swiperImgList.size() > 0) {
            System.out.println(swiperImgList.size() + ":" + swiperList.size());
            if (swiperImgList.size() == swiperList.size()) {
                try {
                    //Hotel hotel = ((Merchant)request.getSession().getAttribute("currentMerchant")).getHotel();
                    Hotel hotel = new Hotel();
                    hotel.sethId(3);
                    for (Swiper swiper : swiperList) {
                        if (swiper != null) {
                            swiper.setHotel(hotel);
                        }
                    }
                    System.out.println("Set hotel for swipers");
                    SwiperOperationExecution execution = swiperService.batchInsertSwiper(swiperList, swiperImgList);
                    System.out.println("Has insert info");
                    if (execution.getState() != 0) {
                        modelMap.put("success", false);
                        modelMap.put("errMsg", execution.getStateInfo());
                        System.out.print(modelMap);
                        return JSON.toJSONString(modelMap);
                    }
                    modelMap.put("success", true);
                    modelMap.put("msg", execution.getStateInfo());
                } catch (Exception e) {
                    throw new SwiperOperationException("SwiperController-addaddSwipers,在处理轮播图文字信息的过程中发生异常：" + e.toString());
                }
            } else {
                modelMap.put("success", false);
                modelMap.put("errMsg", "请完善您的轮播图相关信息后再提交！");
                System.out.print(modelMap);
                return JSON.toJSONString(modelMap);
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请至少输入一张轮播图的详细信息");
            System.out.print(modelMap);
            return JSON.toJSONString(modelMap);
        }
        System.out.print("返回数据：" + modelMap);
        return JSON.toJSONString(modelMap);
    }
//    /**
//     * 商家多条件检索所有轮播图
//     * @param swiper
//     * @return
//     */
//    @RequestMapping(value="/merchantsRetrieveSwiper")
//    @ResponseBody
//    public Map<String ,Object> merchantsRetrieveSwiper(Swiper swiper){
//        Hotel hotel = new Hotel();
//        hotel.sethId(3);
//        swiper.setHotel(hotel);
//        return swiperService.merchantsRetrieveSwiper(swiper);
//    }

    /**
     * 商家批量删除轮播图
     *
     * @return
     */
    @RequestMapping(value = "/deleteSwiperById")
    @ResponseBody
    public Map<String, Object> deleteSwiperById(List<Swiper> list) {
        return swiperService.deleteSwiperById(list);
    }


    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getServletContext());
            if (resolver.isMultipart(request)) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                MultipartFile file = multipartRequest.getFile("swiperImg0");
                modelMap.put("fileName", file.getOriginalFilename());
                List<Swiper> swiperList = new ArrayList<Swiper>();
                String swipers = request.getParameter("swiperList");
                JSONArray jsonArray = JSONArray.fromObject(swipers);
                swiperList = JSONArray.toList(jsonArray, Swiper.class);
                System.out.println(swiperList.size());
                for (Swiper swiper : swiperList) {
                    System.out.print(swiper);
                }
                System.out.print(modelMap);
            }
        } catch (Exception e) {
            throw new RuntimeException();
        }
        return JSON.toJSONString(modelMap);
    }


    @RequestMapping(value = "/updateSwiper")
    @ResponseBody
    public String modifySwiper(HttpServletRequest request) throws IOException {
        Map<String, Object> modelMap = new HashMap<String, Object>();

        ObjectMapper mapper = new ObjectMapper();
        String swiperStr = request.getParameter("swiperStr");
        Swiper swiper = mapper.readValue(swiperStr, Swiper.class);

        System.out.println(swiper);

        ImageHolder swiperImg = null;
        //从Servlet容器中获取CommonsMultipart解析器
        CommonsMultipartResolver multipartResolver =
                new CommonsMultipartResolver(request.getServletContext());

        System.out.println(multipartResolver.isMultipart(request));

        //首先获取图片信息
        try {
            if (multipartResolver.isMultipart(request)) {
                //把Swiper的图片信息写入到swiperImgList中去
                swiperImg = ImageHandle.handleImage(request);
            } else {
                modelMap.put("success", false);
                modelMap.put("errMsg", "上传图片不能为空");
                System.out.println(modelMap);
                return JSON.toJSONString(modelMap);
            }
        } catch (Exception e) {
            throw new SwiperOperationException("SwiperController-addaddSwipers,在处理轮播图信息的过程中发生异常：" + e.toString());
        }
        //取出图片信息后，验证文本信息是否正确
        System.out.println("----------------------------");
        if (swiper != null && swiper.getSwName() != null && swiper.getSwDesc() != null && swiperImg != null) {
            try {
                //Hotel hotel = ((Merchant)request.getSession().getAttribute("currentMerchant")).getHotel();
                Hotel hotel = new Hotel();
                hotel.sethId(3);
                swiper.setHotel(hotel);
                System.out.println("Set hotel for swipers");
                SwiperOperationExecution execution = swiperService.updateSwiper(swiper, swiperImg);
                System.out.println("Has insert info");
                if (execution.getState() != 0) {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", execution.getStateInfo());
                    return JSON.toJSONString(modelMap);
                }
                modelMap.put("success", true);
                modelMap.put("msg", execution.getStateInfo());
            } catch (Exception e) {
                throw new SwiperOperationException("SwiperController-addaddSwipers,在处理轮播图文字信息的过程中发生异常：" + e.toString());
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请完善您的轮播图相关信息后再提交！");
            return JSON.toJSONString(modelMap);
        }
        System.out.print("返回数据：" + modelMap);

        return JSON.toJSONString(modelMap);
    }

    /**
     * 按照主键查询轮播图
     *
     * @param swiperId
     * @return
     */
    @RequestMapping(value = "/selectOneSwiperById")
    @ResponseBody
    public Map<String, Object> selectOneSwiperById(Integer swiperId) {
        return swiperService.selectOneSwiperById(swiperId);
    }
}
